from django.shortcuts import render, HttpResponse

# Create your views here.
from utils.sms import send_sms_single  # 导入发送短信函数
from django.conf import settings
import random

from django import forms
from app01 import models

from django.core.validators import RegexValidator


def send_sms(request):
    """发送短信"""
    # 根据用户请求不同 修改模板id （登录 或者注册）
    # ?type=login
    # ?type=register
    type_name = request.GET.get('type')
    template_id = settings.TENCENT_SMS_TEMPLATE.get(type_name)
    if not template_id:
        return HttpResponse('模板不存在')
    code = random.randrange(1000, 9999)
    res = send_sms_single('18761661318', template_id, [code, ])
    print(res)
    if res['result'] == 0:
        return HttpResponse('发送成功')
    else:
        return HttpResponse(res['errmsg'])


# 注册
class RegisterModeForm(forms.ModelForm):
    # 重写原字段属性,如果没有这个字段则创建新的，如果有则覆盖
    mobile_phone = forms.CharField(label="手机号码", max_length=11,
                                   # 匹配手机号格式
                                   validators=[RegexValidator(r'^(1[[|3|4|5|6|7|8|9|])\d{9}$', '手机号格式错误'), ])
    password = forms.CharField(label='密码', max_length=32, widget=forms.PasswordInput)  # 改为密文输入
    re_password = forms.CharField(label='确认密码', max_length=32, widget=forms.PasswordInput)
    code = forms.CharField(label='验证码')

    class Meta:
        model = models.UserInfo
        # 按照自己需求顺序展示字段
        fields =['username','email','password','re_password','mobile_phone','code']

    # 初始化参数，为每个字段都添加form 类属性
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            # name : 数据库的字段名
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = '请输入%s' % field.label


def register(request):
    """注册"""
    form = RegisterModeForm()
    return render(request, 'app01/register.html', {'form': form})
